<?php

namespace App\Admin\Controllers;
use Dcat\Admin\Admin;
use Dcat\Admin\Controllers\AuthController as BaseAuthController;
use Dcat\Admin\Form;
use Dcat\Admin\Models\Administrator as AdminUserModel;
use Dcat\Admin\Models\Repositories\Administrator;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class AuthController extends BaseAuthController {

	/**
	 * 重写登录
	 *
	 * @param Request $request
	 *
	 * @return mixed
	 */
	public function postLogin(Request $request) {

		$credentials = $request->only([$this->username(), 'password']);
		$remember = (bool) $request->input('remember', false);

		/** @var \Illuminate\Validation\Validator $validator */
		$validator = Validator::make($credentials, [
			$this->username() => 'required',
			'password' => 'required',
		]);

		if ($validator->fails()) {
			return $this->validationErrorsResponse($validator);
		}
		$res = false;
		try {
			$res = $this->guard()->attempt($credentials, $remember);
		} catch (\Exception $e) {
			return $this->validationErrorsResponse([
				$this->username() => "登录接口异常" . $e->getMessage(),
			]);
		}
		if ($res) {
			//更新登录时间和ip
			AdminUserModel::where("id", '=', Admin::user()->id)
				->limit(1)->update([
				'login_time' => time(),
				'login_ip' => get_client_ip(),
			]);
			return $this->sendLoginResponse($request);
		}

		return $this->validationErrorsResponse([
			$this->username() => $this->getFailedLoginMessage(),
		]);
	}
	/**
	 * 重写用户信息设置
	 *
	 * @return Form
	 */
	protected function settingForm() {
		$form = new Form(new Administrator());

		$form->action(admin_url('auth/setting'));

		$form->disableCreatingCheck();
		$form->disableEditingCheck();
		$form->disableViewCheck();

		$form->tools(function (Form\Tools $tools) {
			$tools->disableView();
			$tools->disableDelete();
		});

		$form->display('username', trans('admin.username'));
		$form->text('name', trans('admin.name'))->required();
		//将头像上传设置为系统设定的上传驱动
		$form->image('avatar', trans('admin.avatar'))
			->accept('jpg,png,gif,jpeg,bmp,jpg', 'image/*')
			->disableRemove()
			->url("upload");

		$form->password('old_password', trans('admin.old_password'));

		$form->password('password', trans('admin.password'))
			->minLength(5)
			->maxLength(20)
			->customFormat(function ($v) {
				if ($v == $this->password) {
					return;
				}

				return $v;
			});
		$form->password('password_confirmation', trans('admin.password_confirmation'))->same('password');

		$form->ignore(['password_confirmation', 'old_password']);

		$form->saving(function (Form $form) {
			if ($form->password && $form->model()->password != $form->password) {
				$form->password = bcrypt($form->password);
			}

			if (!$form->password) {
				$form->deleteInput('password');
			}
		});

		$form->saved(function (Form $form) {
			return $form->redirect(
				admin_url('auth/setting'),
				trans('admin.update_succeeded')
			);
		});

		return $form;
	}
}
